package java高并发核心编程.多线程.交替打印;

//两个线程交替打印1-100
public class Demo1 {
    private static volatile int number = 1;
    private static final int MAX = 100;
    private static Object monitor = new Object();
    public static void main(String[] args) {
        Thread odd = new Thread(new OddThread(), "奇数线程");
        Thread even = new Thread(new EvenThread(), "偶数线程");
        odd.start();
        even.start();
    }

    //奇数线程
    static class OddThread implements Runnable {
        @Override
        public void run() {
            while (number < MAX) {
                synchronized (monitor) {
                    while (number % 2 == 0) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "-->" + number);
                    number++;
                    monitor.notify();
                }
            }
        }
    }

    //偶数线程
    static class EvenThread implements Runnable {

        @Override
        public void run() {
            while (number <= MAX) {
                synchronized (monitor) {
                    while (number % 2 != 0) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "-->" + number);
                    number++;
                    monitor.notify();
                }
            }
        }
    }
}
